package com.sgy.zookeeper_api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class GetNoteData implements Watcher {

    // 允许等待一个线程
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /*
        建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        /*
        * connectString：连接地址（ip:port）
        * sessionTimeout：会话超时时间
        * watcher：监听器
        * */
        zooKeeper = new ZooKeeper("192.168.201.129:2181", 30000, new GetNoteData());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent.getState());
        // SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 获取节点数据
            try {
                getNoteData();
                getChildrens();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
        }

        /*
        * 当子节点列表发生改变时，服务器端会发出noteChildrenChanged事件通知，重新获取子节点列表
        * noteChildrenChanged事件通知是一次性的，需要反复注册监听
        * */
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            List<String> children = null;
            try {
                children = zooKeeper.getChildren("/zk-persisent", true);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(children);
        }
    }

    /**
     * 获取节点内容
     */
    private void getNoteData() throws InterruptedException, KeeperException {
        /**
         * path : 获取数据的路径
         * watch : 是否开启监听
         * stat : 节点状态信息
         *         null: 表示获取最新版本的数据
         */
        byte[] data = zooKeeper.getData("/zk-persisent", false, null);
        System.out.println(new String(data));
    }

    /**
     * 获取某个节点的子节点列表的方法
     */
    private static void getChildrens() throws InterruptedException, KeeperException {
        /*
            path:路径
            watch:是否要启动监听，当⼦节点列表发⽣变化，会触发监听
        */
        List<String> children = zooKeeper.getChildren("/zk-persisent", true);
        System.out.println(children);
    }
}
